/**
 * 定义RemoteControlController远程控制
 */
(function(window, angular, undefined){

	var DataModificationController = angular.module('water.apps.voc.dataModification.connectionCertificateManager', ['ui.router','itfreer','waterCommon','RemoveControlService']);
		
	/**
	 * 修约凭证管理控制器
	 */
	DataModificationController.controller('ConnectionCertificateManager',	['$rootScope','$scope','$itfreerHttp','$waterDataCommon','$ReportService','UploadService','DateService','OperationStationJobService','$NavService', function($rootScope,$scope,$itfreerHttp,$waterDataCommon,$ReportService,UploadService,DateService,OperationStationJobService,$NavService){
		if($rootScope.waterType == "1"){
			$scope.dataSourceSelect = [{"k":"6","v":"周期数据"},{"k":"4","v":"天数据"}];
			$scope.dataSource = "4"; //默认是小时数据
		}
		else{
			$scope.dataSourceSelect = [{"k":"4","v":"天数据"},{"k":"3","v":"小时数据"}];
			$scope.dataSource = "4"; //默认是小时数据
		}
		$scope.uploadStatusCommonData = [{"k":"1","v":"全部"},{"k":"2","v":"已上传"},{"k":"3","v":"未上传"}];
		$ReportService.setSelectedTab("modify.connection");
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.wwtpReportParm = data;
			$scope.STATION_ID=$scope.wwtpReportParm.STATION_ID;
			$scope.STATION_NAME = $scope.wwtpReportParm.STATION_NAME;
			$scope.stationNameCommonData=[{"k":"1","v":"全部"},{"k":$scope.STATION_ID,"v":$scope.STATION_NAME}];
			$scope.queryModifyDataStatus();
	    });
		
		/**
		 * 初始化查询条件
		 */
		function initQueryObj(){
			var nowDate = new Date();
			$scope.hourDate=nowDate.getFullYear()+"-"+(nowDate.getMonth()+1)+"-"+nowDate.getDate();
			
			$scope.yearlist=[];
			var currentYear=(new Date()).getFullYear();
			
			$scope.yearList = [];
			for(var i=0;i<4;i++){
				$scope.yearList.push({
					text:currentYear-i+"年",
					id:currentYear-i+""
				});
			}; 
			$scope.dayYear=currentYear+"";
			$scope.monthlist=[];
			for(var i=1;i<=12;i++){
				$scope.monthlist.push({
					text:i+"月",
					id:""+i
				});
			};
			$scope.dayMonth=((new Date()).getMonth() + 1)+"";
		}
		$scope.queryModifyDataStatus = function(){
			var queryObj = {};
			if($scope.dataSource=='3') {
				queryObj.START = $scope.hourDate+" 00:00:00";
				queryObj.END = $scope.hourDate+" 23:59:59";
			} else {
				queryObj.START = $scope.dayYear+"-"+ $scope.dayMonth+"-01" + " 00:00:00";
				queryObj.END = parseYearEndMonth($scope.dayYear,$scope.dayMonth);
			}
			queryObj.CERTIFICATE_ID = $scope.uploadStatus;
			queryObj.MN = $scope.stationID;
			queryObj.WATER_TYPE = getWaterType();
			queryObj.TABLE_FLAG = $scope.dataSource;
			$waterDataCommon.getPageRows("/DataModification/getModifiedRecordByCertifyStatus.do","ModifyDataCerfityStatusList",queryObj,10,1,function(data){
				$scope.result = data.data;
				
			});
		};
		$scope.certObj = {CERTIFICATE_NAME:'',REMARK:''};
		$scope.rowData={};
		$scope.addCertificate = function(curRow){
			$scope.modifyDate = curRow.MODIFY_DATE;
			$scope.rowData.MN = curRow.MN;
			$scope.rowData.GUID=curRow.GUID;
			$scope.fileList = [];
			$scope.certObj = {CERTIFICATE_NAME:'',
					REMARK:'',
					USER_NAME:($scope.currentUser.S_USERID==-1?'超级管理员':$scope.currentUser.C_USEREALNAME),
					USER_ID:$scope.currentUser.S_USERID};
			$scope.certificate_type.type = '0';
			$itfreer.openWindow('AddCertificate',{width:800,height:250});
		};
		//查看/编辑凭证
		$scope.viewOrEditCertificate = function(curRow){
			$scope.fileList = [];
			$scope.updateUserID = curRow.UPDATEUSERID;
			$scope.updateUserName = curRow.UPDATEUSERNAME;
			queryCertificateFile(curRow.GUID,function(r){
				if(r && r.data){
					angular.forEach(r.data,function(value,key){
						$scope.fileList.push(value);
					});
					$scope.certObj.USER_ID = curRow.USER_ID;
					$scope.certObj.USER_NAME = curRow.USER_ID==-1?'超级管理员': curRow.C_USEREALNAME;
					$scope.certObj.CERTIFICATE_NAME = curRow.CERTIFICATE_NAME;
					$scope.certificate_type.type = curRow.CERTIFICATE_TYPE;
					$scope.certObj.REMARK = curRow.REMARK;
					$scope.rowData.GUID=curRow.GUID;
					$scope.rowData.MN=curRow.MN;
					$scope.rowData.MODIFY_DATE=curRow.MODIFY_DATE;
					$itfreer.openWindow('AddCertificate',{width:800,height:250});
				}
			});
		};
		$scope.certificate_type = {list:[{name:'企业异常',type:'0'},{name:'企业停水',type:'2'},{name:'企业停产',type:'3'},{name:'设备故障',type:'4'},{name:'其他',type:'1'}],type:'0'};
		//保存凭证
		$scope.saveCertificate = function(curRow){
			if($scope.fileList.length>0){
				//首先做一个文件类型的上传控制
				var flag = false;
				var typeArray = ["jpg",".jpeg","pdf","doc","docx"];
				var fileObj = $scope.fileList[0].FILE_PATH;
				var lastIndex = fileObj.lastIndexOf(".");
				var fileType = fileObj.substring(lastIndex+1,fileObj.length);
				for (var i = 0;i<typeArray.length;i++) {
					if(fileType==typeArray[i]) {
						flag=true;
					}
				}
				if(flag==false) {
					$.messager.alert("提示","凭证类型限于(*.pdf;*.jpg;*.jpeg;*.doc;*.docx;)");
					return false;
				}
				var saveObj = {};
				saveObj.CERTIFICATE_NAME = $scope.certObj.CERTIFICATE_NAME;
				saveObj.REMARK = $scope.certObj.REMARK;
				saveObj.CERTIFICATE_TYPE = $scope.certificate_type.type;
				saveObj.USER_ID = $scope.certObj.USER_ID;
				saveObj.CREATE_TIME = DateService.addDateTime();
				saveObj.GUID = $scope.rowData.GUID;
				saveObj.MN = $scope.rowData.MN;
				saveObj.MODIFY_DATE = $scope.modifyDate;
				saveObj.dataSource = $scope.dataSource;
				saveObj.water_type = getWaterType();
				OperationStationJobService.postQuery("/DataModification/saveCertificate.do",saveObj).then(function(d){
					if(d){
						var list = [];
						angular.forEach($scope.fileList,function(value,key){
							list.push(value.FILE_PATH);
						});
						if(list.length && d.GUID){
							saveObj.FILES = list.toString();
							saveObj.CERTIFICATE_ID = d.GUID;
							OperationStationJobService.postQuery("/DataModification/saveCertificateFileList.do",saveObj).then(function(r){
								$itfreer.closeWindow("AddCertificate");
								$.messager.alert("提示","保存成功");
								$scope.queryCertificate();
				            });
						}
						else{
							$itfreer.closeWindow("AddCertificate");
							$.messager.alert("提示","保存成功");
							$scope.queryCertificate();
						}
						$scope.queryModifyDataStatus();
					}
				});
		   }
			else{
				$.messager.alert("提示","文件不能为空！");
			}
		};
		//查看上传的凭证文件
		$scope.viewCertificate = function(id){
			$itfreer.openWindow('CertificateDetail',{width:800,height:250});
			$waterDataCommon.getPageRows("/DataModification/getCertificateInfo.do","CertificateInfo",{CERTIFICATE_ID:id},10,1,function(r){
				$scope.certificate = r;
			});
		}
		
		//删除凭证文件
		$scope.deleteCertificateFile = function(curRow){
			var certifid = curRow.CERTIFICATE_ID;
			$.messager.confirm("确认","确定要删除吗？",function(r){
				if(r){
					$itfreerHttp.deleteByKey("MONITOR_DATA_CERTIFICATE_FILE", {GUID:curRow.GUID},function(){
						queryCertificateFile(curRow.CERTIFICATE_ID,function(r){
							if(r && r.data){
								$scope.fileList=[];
								angular.forEach(r.data,function(value,key){
									$scope.fileList.push(value);
								});
							}
						});
					})
					$scope.updateModifyDataCertifiedId(certifid);
					$scope.deleteMonitorDataCertificate(certifid);
					$scope.queryModifyDataStatus();
				}
			});
		};
		$scope.updateModifyDataCertifiedId = function(certifid){
			var saveObj = {};
			saveObj.CERTIFICATE_ID = certifid;
			saveObj.MN = $scope.rowData.MN;
			saveObj.MODIFY_DATE = $scope.rowData.MODIFY_DATE;
			saveObj.dataSource = $scope.dataSource;
			OperationStationJobService.postQuery("/DataModification/updateModifiedCerticateId.do",saveObj).then(function(r){
            });
		};
		$scope.deleteMonitorDataCertificate = function(guid){
			$itfreerHttp.deleteByKey("MONITOR_DATA_CERTIFICATE", {GUID:guid},function(){
			})
		};
		//下载凭证文件
		$scope.downloadFile = function(curRow){
			var fileInfo = curRow.FILE_PATH;
			if (!fileInfo) return;
			fileInfoArr = fileInfo.split(":");
			var url = fileInfoArr[0];
			var name = fileInfoArr[1];
			var downloadUrl = getBasePath()+'/plupload/download.do';
			var _downloadUrl = downloadUrl+"?filePath="+url.replace(getBasePath()+"/","")+"&fileName="+encodeURIComponent(name);
			window.open(_downloadUrl);
		};
		//删除凭证
		$scope.deleteCertificate = function(curRow){
			var obj = {'CERTIFICATE_ID':curRow.GUID};
			var msg = '';
			OperationStationJobService.postQuery("/DataModification/getModifyDataCountByCertificate.do",obj).then(function(r){
				if(r){
					if(r.rowcount==0){
						msg = '确定要删除记录吗？';
					}else{
						msg = '当前凭证已经关联了修约数据，确定要删除吗？';
					}
					$.messager.confirm('确认',msg,function(yes){
						if(yes){
							OperationStationJobService.postQuery("/DataModification/deleteCertificate.do",obj)
							.then(function(r){
								if(r && r.data=='success'){
									$.messager.alert("提示","删除成功！");
								}else{
									$.messager.alert("提示","删除失败！");
								}
								$scope.queryCertificate();
							});
						}
					});
				}
            });
		};
		
		//上传凭证文件
		$scope.fileList = [];
		function uploadSuccessHandler(fileInfo){
			$scope.fileList.push({"FILE_PATH":fileInfo.file});
			$scope.$apply();
		}
		//查询凭证文件
		function queryCertificateFile(certificate_id,callback){
			var queryObj = {};
			queryObj.CERTIFICATE_ID = certificate_id;
			$waterDataCommon.getPageRows("/DataModification/getCertificateFileList.do","CertificateFileList",queryObj,10,1,callback);
		}
		//上传凭证文件
		$scope.uploadCertificateFile = function(){
			UploadService.upload(uploadSuccessHandler);
		};
		
		$scope.closeCertWindow = function(){
			$itfreer.closeWindow("AddCertificate");
		}
		
		/**
		 * 获取结束日期
		 */
       function parseYearEndMonth(year, month){
			
			var end_day = new Date(year,month,0); 
			var endday = '' + end_day.getDate();
			
			if(endday.length==1){
				endday = '0' + endday;
			}
			var end_month = '' + month;
			if(end_month.length==1) {
				end_month = '0' + end_month;
			}
			
			var end_date = year + '-' + end_month + '-' + endday;
			return end_date+ " 23:59:59";
		}
		$scope.waterDataCommon = $waterDataCommon;
		initQueryObj();
	}]);	
	
}(window, angular));